<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="类型名称"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="brief">
        <el-input  v-model="dataForm.brief" placeholder="简介"></el-input>
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select @change="handlerCateChange" v-model="dataForm.parentId" placeholder="请选择上级分类">
          <el-option
            v-for="(item, index) in cateList"
            :key="index"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="1!==1">
        <div>{{num}}</div>
      </el-form-item>
      <el-form-item label="类型" prop="type" v-show="typeVisible">
        <el-radio-group v-model="dataForm.type">
          <el-radio @change="handlerChange" v-for="(item, index) in serviceTypeList" :label="item.value" :key="index">
            {{item.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
<!--      <el-form-item label="path">-->
<!--        <el-input v-model="dataForm.path" placeholder="path"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item label="排序" prop="sort">
        <el-input type="Number" v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>
      <el-form-item label="图标(1:1)">
        <el-upload
          :action="actionUrl"
          :headers="headers"
          :limit="1"
          :file-list="fileList"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :on-remove="handleImageRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-if="createState=='create'" @click="dataFormSubmit()">保存</el-button>
      <el-button type="primary" v-else @click="dataFormUpdate()">更新</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'
  import {handleImgUrl} from '@/utils/util'
  import { getObj, addObj, putObj } from '@/api/merchantservices/merservicestype'
  export default {
    data() {
      return {
        headers: {
          'token': Vue.cookie.get('token')
        },
        cateList: [],
        createState: 'create',
        typeVisible: true,
        fileList: [],
        visible: false,
        actionUrl: '',
        num: 0,
        serviceTypeList: [],
        dataForm: {
          id: '',
          name: '',
          type: '',
          parentId: -1,
          sort: 100,
          icon: '',
          brief: '',
        },
        dataRule: {
          name: [
            {required: true, message: '类型名称不能为空', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '类型不能为空', trigger: 'change'}
          ],
          sort: [
            {required: true, message: '排序不能为空', trigger: 'blur'}
          ],
          brief: [
            {required: true, message: '简介不能为空', trigger: 'blur'}
          ],
          parentId: [
            {required: true, message: '上级分类不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    mounted: function () {
      this.actionUrl = this.$http.adornUploadUrl()
    },
    methods: {
      init(id) {
        this.getServicesTypeListByDictType()
        this.getMerServicesTypeList()
        this.dataForm.id = id
        if (id) {

          this.createState = 'update'
        } else {
          this.createState = 'create'
        }
        this.fileList = []
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            getObj(this.dataForm.id)
              .then(res => {
                this.dataForm.name = res.data.data.name
                this.dataForm.parentId = res.data.data.parentId
                this.dataForm.type = res.data.data.type + ''
                this.dataForm.sort = res.data.data.sort
                this.dataForm.icon = res.data.data.icon
                this.dataForm.brief = res.data.data.brief
                if (res.data.data.icon) {
                  handleImgUrl(res.data.data.icon).then((res) => {
                    this.fileList = [{
                      url: res.data
                    }]
                  })
                } else {
                  this.fileList = []
                }
              })
            // this.$http({
            //   url: this.$http.adornUrl(`/generator/brandtype/info/${this.dataForm.id}`),
            //   method: 'get',
            //   params: this.$http.adornParams()
            // }).then(({data}) => {
            //   if (data && data.code === 0) {
            //     this.dataForm.name = data.brandtype.name
            //     this.dataForm.isShow = data.brandtype.isShow
            //     this.dataForm.isDel = data.brandtype.isDel
            //     this.dataForm.sort = data.brandtype.sort
            //     this.dataForm.cTime = data.brandtype.cTime
            //   }
            // })
          }
        })
      },
      // 获取字典中服务类型列表
      getServicesTypeListByDictType() {
        this.$http({
          url: this.$http.adornUrl("/sys/dict/type/services_type"),
          method: 'get'
        }).then(res => {
          this.serviceTypeList = res.data.data
          if (this.serviceTypeList && this.serviceTypeList.length > 0) {
            this.dataForm.type = this.serviceTypeList[0].value
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (!this.dataForm.type) {
            this.$message.error('类型不能为空')
            return
          }
          if (valid) {
            addObj({
              'name': this.dataForm.name,
              'parentId': this.dataForm.parentId,
              'type': this.dataForm.type,
              'sort': this.dataForm.sort,
              'icon': this.dataForm.icon,
              'path': this.dataForm.path,
              'brief': this.dataForm.brief,
            }).then(res => {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
              })
              this.visible = false
              this.$emit('refreshDataList')
            })
            // this.$http({
            //   url: this.$http.adornUrl('/merchantservices/merservicestype'),
            //   method: 'post',
            //   data: this.$http.adornData({
            //     'id': this.dataForm.id || undefined,
            //     'name': this.dataForm.name,
            //     'isShow': this.dataForm.isShow,
            //     'isDel': this.dataForm.isDel,
            //     'sort': this.dataForm.sort,
            //     'cTime': this.dataForm.cTime
            //   })
            // }).then(({data}) => {
            //   if (data && data.code === 0) {
            //     this.$message({
            //       message: '操作成功',
            //       type: 'success',
            //       duration: 1500,
            //       onClose: () => {
            //         this.visible = false
            //         this.$emit('refreshDataList')
            //       }
            //     })
            //   } else {
            //     this.$message.error(data.msg)
            //   }
            // })
          }
        })
      },
      // 表单更新
      dataFormUpdate() {
        this.$refs['dataForm'].validate((valid) => {
          if (!this.dataForm.type) {
            this.$message.error('类型不能为空')
            return
          }
          if (valid) {
            putObj({
              'id': this.dataForm.id,
              'name': this.dataForm.name,
              'parentId': this.dataForm.parentId,
              'type': this.dataForm.type,
              'sort': this.dataForm.sort,
              'icon': this.dataForm.icon,
              'brief': this.dataForm.brief,
            }).then(res => {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
              })
              this.visible = false
              this.$emit('refreshDataList')
            })
          }
        })
      },
      handlerChange() {
        this.num++
      },
      handleUploadSuccess(res, file) {
        this.dataForm.icon = res.data.bucketName + "-" + res.data.fileName;
      },
      handleImageRemove() {
        this.dataForm.icon = ''
      },
      // 获取所有商家服务分类
      getMerServicesTypeList() {
        this.$http({
          url: this.$http.adornUrl("/merchantservices/merservicestype/tree"),
          method: 'get'
        }).then(res => {
          this.cateList = res.data.data
          this.cateList.unshift({
            id: -1,
            name: '顶级分类'
          })
        })
      },
      handlerCateChange(val) {
        this.dataForm.type = ''
        if (!val || val === -1) {
          this.typeVisible = true
        } else {
          this.typeVisible = false
          //获取当前类型
          getObj(val)
            .then(res => {
              this.dataForm.type = res.data.data.type
            })
        }
      }
    }
  }
</script>
